package com.ruyuan.user.server.controller;

import com.ruyuan.common.model.BusinessException;
import com.ruyuan.common.model.ErrorCode;
import com.ruyuan.common.model.PageDTO;
import com.ruyuan.common.web.model.WebResponse;
import com.ruyuan.gateway.sdk.facade.RuyuanGatewayFacade;
import com.ruyuan.gateway.sdk.model.UserAccountInfo;
import com.ruyuan.user.api.model.constants.UserAccountInfoExtendKeys;
import com.ruyuan.user.server.controller.converter.WebOrganizationConverter;
import com.ruyuan.user.server.controller.request.DelOrganizationRequest;
import com.ruyuan.user.server.controller.request.SaveOrganizationRequest;
import com.ruyuan.user.server.controller.response.OrganizationTreeVO;
import com.ruyuan.user.server.domain.model.Organization;
import com.ruyuan.user.server.domain.service.OrganizationDomainService;
import com.ruyuan.user.server.domain.service.request.PageQueryOrganizationParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author xx
 */
@Controller
@RequestMapping("/api/user/org")
public class OrganizationController {

    @Autowired
    private WebOrganizationConverter converter;

    @Autowired
    private OrganizationDomainService organizationDomainService;

    @Autowired
    private RuyuanGatewayFacade ruyuanGatewayFacade;

    @RequestMapping("/save")
    @ResponseBody
    public WebResponse<Long> saveOrg(@Validated @RequestBody SaveOrganizationRequest request, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return WebResponse.failWithMsg(bindingResult.getFieldError().getDefaultMessage());
        }
        Organization organization = converter.convertRequestToOrganization(request);
        Long orgId = organizationDomainService.saveOrganization(organization);
        return WebResponse.successWithData(orgId);
    }

    @RequestMapping("/queryTree")
    @ResponseBody
    public WebResponse<List<OrganizationTreeVO>> queryOrgTree() {
        UserAccountInfo currentUser = ruyuanGatewayFacade.getCurrentUser();
        String rootOrgId = currentUser.getExtendInfo().get(UserAccountInfoExtendKeys.ROOT_ORG_ID);
        if (StringUtils.isBlank(rootOrgId)) {
            return WebResponse.failWithMsg("当前用户不属于任何组织");
        }
        PageQueryOrganizationParam param = new PageQueryOrganizationParam();
        param.setCurrent(1);
        param.setRootOrgId(Long.parseLong(rootOrgId));
        param.setPageSize(1000);
        PageDTO<Organization> pageDTO = organizationDomainService.queryOrganizationByCondition(param);
        List<Organization> list = pageDTO.getData();
        if (CollectionUtils.isEmpty(list)) {
            return WebResponse.successWithData(new ArrayList<>());
        }
        List<OrganizationTreeVO> voList = converter.convertModelToTreeVOList(list);
        return WebResponse.successWithData(voList);
    }

    @RequestMapping("/del")
    @ResponseBody
    public WebResponse<Boolean> delOrg(@Validated @RequestBody DelOrganizationRequest request, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return WebResponse.failWithMsg(bindingResult.getFieldError().getDefaultMessage());
        }
        UserAccountInfo currentUser = ruyuanGatewayFacade.getCurrentUser();
        //如果当前组织下面有子组织，就不能删除
        PageQueryOrganizationParam param = new PageQueryOrganizationParam();
        param.setRootOrgId(Long.valueOf(currentUser.getExtendInfo().get(UserAccountInfoExtendKeys.ROOT_ORG_ID)));
        param.setCurrent(1);
        param.setPageSize(1);
        param.setParentId(request.getOrgId());
        PageDTO<Organization> pageDTO = organizationDomainService.queryOrganizationByCondition(param);
        if (!CollectionUtils.isEmpty(pageDTO.getData())) {
            return WebResponse.failWithMsg("当前组织下面有子组织，无法删除");
        }

        Organization organization = organizationDomainService.queryOrganizationById(request.getOrgId());
        if (organization == null) {
            return WebResponse.failWithMsg("要删除的组织不存在");
        }
        //不允许删除根节点，视业务诉求而定
        if (Objects.equals(organization.getRootId(), organization.getId())) {
            return WebResponse.failWithMsg("不能删除根节点");
        }
        organization.setIsDeleted(true);
        organization.setModifier(String.valueOf(currentUser.getUserId()));
        organizationDomainService.saveOrganization(organization);
        return WebResponse.successWithData(true);
    }

}
